﻿using System;
using System.IO;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Net;
using System.Xml;
using System.Globalization;

namespace Alfred
{
	class Wiki
	{
		private List<String> keywords;

		public string title { get; set; }
		public string content { get; set; }

		public void LoadFromQuery(string query)
		{
			string result = TryDirectSearch(query);
			if (result == "no")
				AddKeywords(query);
			else
				ParseFromText(result);
		}

		public void ParseFromText(string result)
		{
			XmlDocument doc = new XmlDocument();
			doc.LoadXml(result);
			XmlNode rev = doc.GetElementsByTagName("rev")[0];
			
			Regex r = new Regex(@"\{\{([^{|]+)\|([^{|]+)\}\}");
			string newS = r.Replace(rev.InnerText, "$2");

			r = new Regex(@"\{\{([^{]+)\}\}");
			newS = r.Replace(newS, "$1");

			r = new Regex(@"\[\[([^[]+)\|([^[]+)\]\]");
			newS = r.Replace(newS, "$2");

			r = new Regex(@"\[\[([^[]+)\]\]");
			newS = r.Replace(newS, "$1");

			r = new Regex(@"\[([^[]+)\]");
			newS = r.Replace(newS, "");

			this.content = newS;
		}

		public void AddKeywords(string s)
		{
			HttpWebRequest myRequest = (HttpWebRequest)WebRequest.Create("http://fr.wikipedia.org//w/api.php?action=query&list=search&format=xml&prop=&srsearch=" + s + "&srlimit=5");
			myRequest.Timeout = 10000; // 10 secs
			myRequest.UserAgent = "Code Sample Web Client";
			myRequest.Accept = "text/xml";
			HttpWebResponse response = (HttpWebResponse)myRequest.GetResponse();
			string ResponseText;
			using (StreamReader reader = new StreamReader(response.GetResponseStream()))
			{
				ResponseText = DecodeEncodedNonAsciiCharacters(reader.ReadToEnd());
				XmlDocument doc = new XmlDocument();
				doc.LoadXml(ResponseText);
				XmlNodeList l = doc.GetElementsByTagName("p");
				keywords = new List<string>();
				foreach (XmlNode x in l)
					keywords.Add(x.Attributes["title"].Value);
			}
		}

		public string TryDirectSearch(string s)
		{
			HttpWebRequest myRequest = (HttpWebRequest)WebRequest.Create("http://fr.wikipedia.org/w/api.php?action=query&prop=revisions&format=xml&redirects&titles=" + s + "&rvprop=content");
			myRequest.Timeout = 10000; // 10 secs
			myRequest.UserAgent = "Code Sample Web Client";
			myRequest.Accept = "text/xml";
			HttpWebResponse response = (HttpWebResponse)myRequest.GetResponse();
			string ResponseText;
			using (StreamReader reader = new StreamReader(response.GetResponseStream()))
			{
				ResponseText = DecodeEncodedNonAsciiCharacters(reader.ReadToEnd());
				if (ResponseText.Length > 200) return ResponseText;
				else return "no";
			}
		}

		static string DecodeEncodedNonAsciiCharacters(string value)
		{
			return Regex.Replace(
				value,
				@"\\u(?<Value>[a-zA-Z0-9]{4})",
				m =>
				{
					return ((char)int.Parse(m.Groups["Value"].Value, NumberStyles.HexNumber)).ToString();
				});
		}
	}
}
